package com.grupoconstruobras.sigo.general.interceptores;

import com.grupoconstruobras.sigo.general.util.ManagedBeanUtils;
import com.grupoconstruobras.sigo.general.util.security.PermissionAdapter;

import java.io.IOException;
import java.security.Principal;

import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialViewContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class RestoreViewPhaseListener implements PhaseListener {
	
	public static final String ANONYMOUS = "anonymous"; 

	/**
   * 
   */
	private static final long serialVersionUID = -5887573043445030946L;

	private static final Logger log = Logger.getLogger("SIJYP");

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		HttpServletRequest httpRequest = (HttpServletRequest) facesContext
				.getExternalContext().getRequest();
		HttpServletResponse httpResponse = (HttpServletResponse) facesContext
				.getExternalContext().getResponse();

		Principal principal = httpRequest.getUserPrincipal();
		
		PermissionAdapter permissionAdapter = facesContext.getApplication()
				.evaluateExpressionGet(facesContext, "#{permissionAdapter}",
						PermissionAdapter.class);
		String currentPage = facesContext.getViewRoot().getViewId();
		boolean isLoginPage = currentPage.lastIndexOf("index.xhtml") != -1;
		
		if(principal != null && !ANONYMOUS.equalsIgnoreCase(principal.getName())) {
			try{  
				boolean isAuthenticated = httpRequest.authenticate(httpResponse);
				
				permissionAdapter.loadAvailablePrincipals();
			} catch(IOException e) {
				log.error(e);
			} catch(ServletException e) {
				log.error(e);
			}
		}

		if (!isLoginPage && (principal == null || ANONYMOUS.equalsIgnoreCase(principal.getName()))) {
			PartialViewContext pvc = facesContext.getPartialViewContext();
			if (pvc.isAjaxRequest()) {
				NavigationHandler nh = facesContext.getApplication()
						.getNavigationHandler();
				nh.handleNavigation(facesContext, null, "loginPage");
			} else {
				try {
					facesContext.getExternalContext().redirect(
							httpRequest.getContextPath() + "/index.xhtml");
				} catch (IOException e) {
					log.error(e);
				}
			}

			/*FIXME: log.warnv("Intento de acceso no autorizado de {0} a {1}",
					httpRequest.getRemoteAddr(), httpRequest.getRequestURL());*/

			String msgTxt = ManagedBeanUtils.getMessagesBundle().getString(
					"general.accesoNoAutorizado");
			facesContext.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, msgTxt, null));
		}

	}

	@Override
	public void beforePhase(PhaseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
